package com.companyname.common;

import java.util.List;

import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.base.core.head.constants.MdcConstants;
import com.base.core.head.vo.WsMessageListVO;
import com.base.core.head.vo.WsMessageObjectVO;
import com.base.core.head.vo.WsMessageVO;
import com.companyname.projecttemplate.ao.ws.WsSessionAO;
import com.companyname.projecttemplate.mapping.WsMapping;
import com.gitee.magic.context.ConverterEditorUtils;

/**
 * 发送消息
 * @author start
 */
@Service
public class SendService {

	@Autowired
	private WsMapping wsMapping;
	
	public void send(Long userId,Long targetId,String bizType,String msgType) {
		WsMessageVO resp=new WsMessageVO(
				null,
				MDC.get(MdcConstants.REQUESTID),
				bizType,
				msgType,
				targetId);
		send(userId,resp);
	}
	
	public <T>void send(Long userId,Long targetId,String bizType,String msgType,T data) {
		WsMessageObjectVO<T> resp=new WsMessageObjectVO<>(
				null,
				MDC.get(MdcConstants.REQUESTID),
				bizType,
				msgType,
				targetId);
		resp.setData(data);
		send(userId,resp);
	}
	
	public <T>void send(Long userId,Long targetId,String bizType,String msgType,List<T> data) {
		WsMessageListVO<T> resp=new WsMessageListVO<>(
				null,
				MDC.get(MdcConstants.REQUESTID),
				bizType,
				msgType,
				targetId);
		resp.setData(data);
		send(userId,resp);
	}
	
	public void send(Long userId,Object resp) {
		
		resp=toCovert(resp);
		
		WsSessionAO ao=new WsSessionAO();
		ao.setUserId(String.valueOf(userId));
		ao.setContent(ConverterEditorUtils.converterObject(resp).toString());
		//TODO:mq下发可先获取通道再下发
//		String channel=wsMapping.channel(String.valueOf(userId)).getData();
		if(wsMapping.online(String.valueOf(userId)).getData()) {
			//在线
			wsMapping.send(ao);
		}else {
			//不在线发送离线消息
		}
	}
	
	public Object toCovert(Object obj) {
		if(!obj.getClass().equals(WsMessageObjectVO.class)) {
			return obj;
		}
		return obj;
	}

}
